<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="../bower_components/vaadin-dialog/vaadin-dialog.html">
<link rel="import" href="../bower_components/paper-button/paper-button.html">
<link rel="import" href="../bower_components/paper-checkbox/paper-checkbox.html">
<link rel="import" href="../bower_components/paper-item/paper-item.html">
<link rel="import" href="../bower_components/paper-input/paper-input.html">
<link rel="import" href="../bower_components/paper-input/paper-textarea.html">
<link rel="import" href="../bower_components/paper-dialog-scrollable/paper-dialog-scrollable.html">
<link rel="import" href="../bower_components/paper-listbox/paper-listbox.html">
<link rel="import" href="../bower_components/iron-behaviors/iron-control-state.html">
<link rel="import" href="../bower_components/iron-collapse/iron-collapse.html">
<link rel="import" href="../bower_components/iron-ajax/iron-ajax.html">
<link rel="import" href="../bower_components/paper-spinner/paper-spinner.html">
<link rel="import" href="metric-menu.html">
<link rel="import" href="custom-graph.html">
<dom-module id="add-graph">
    <template>
        <style include="shared-styles forms">
        :host {
            position: relative;
        }

        #selectTarget {
            position: absolute !important;
            min-width: 300px;
        }

        paper-textarea#juicyScript ::slotted(paper-input-container #inner-editor),
        paper-textarea#juicyScript ::slotted(paper-input-container textarea#textarea) {
            font-family: monospace !important;
            font-size: 12px;
        }

        paper-textarea#juicyScript ::slotted(.floated-label-placeholder) {
            display: none;
        }

        hr {
            margin-left: -24px;
            margin-right: 24px;
        }

        div>h2.textarea-h2 {
            padding-bottom: 0;
        }

        .errormsg-container {
            color: var(--red-color);
        }

        .errormsg-container iron-icon {
            color: inherit;
            vertical-align: bottom;
            padding-right: 8px;
        }

        .add-button {
            background-color: #f1f1f1;
            float: right;
            display: block;
            text-align: right;
            margin-top: 4px;
        }

        .add-button iron-icon {
            color: inherit;
            opacity: 0.32;
        }

        .paper-dialog-scrollable {
            padding: 0 !important;
        }

        .paper-dialog-scrollable paper-item {
            padding-left: 10px !important;
            position: relative;
            cursor: pointer;
            border-bottom: 1px solid #ddd;
        }

        .paper-dialog-scrollable .expand-more {
            position: absolute;
            right: 4px;
        }

        .paper-dialog-scrollable paper-listbox:not(.main) {
            padding: 0 0 0 16px;
        }

        .loader {
            margin: 8px;
            display: block;
            text-align: center;
        }

        .loader paper-spinner {
            padding: 8px
        }

        #customButton {
            width: 100%;
        }

        #customOptions {
            max-width: 500px;
        }
        </style>
        <paper-button on-tap="openDialog" class="add-button">
            <iron-icon icon="icons:add-circle"></iron-icon> Add Graph
        </paper-button>
        <vaadin-dialog id="selectTarget" theme="mist-dialog" with-backdrop>
            <template>
                <h2>Select target for graph</h2>
                <div class="paper-dialog-scrollable">
                    <paper-listbox class="main">
                        <paper-button id="customButton" on-tap="_showCustomGraphDialog" class="blue">Custom</paper-button>
                        <template is="dom-repeat" items="[[responseMetricsArray]]">
                            <metric-menu machine="[[machine.id]]" metric=[[item]]></metric-menu>
                        </template>
                    </paper-listbox>
                    <div class="loader" hidden$="{{!loadingMetrics}}">Loading custom server metrics
                        <br />
                        <paper-spinner active="{{loadingMetrics}}"></paper-spinner>
                    </div>
                </div>
            </template>
        </vaadin-dialog>
        <vaadin-dialog id="customOptions" theme="mist-dialog" with-backdrop>
            <template>
                <custom-graph ssh-key-exists="[[sshKeyExists]]" metric="{{metric}}" machine="{{machine}}" uri="[[uri]]"></custom-graph>
            </template>
        </vaadin-dialog>
        <iron-ajax id="metrics" url="[[_computeMetricsUri(machine.id)]]" handle-as="json" method="GET" contentType="application/json" loading="{{loadingMetrics}}" on-response="_handleMetricResponse" on-error="_handleMetricError">
        </iron-ajax>
    </template>
    <script>
    Polymer({
        is: "add-graph",
        properties: {
            panel: {
                type: Object,
            },
            data: {
                type: Object
            },
            machine: {
                type: Object
            },
            responseMetrics: {
                type: Object,
                value: null
            },
            responseMetricsArray: {
                type: Array,
                value: null
            },
            target: {
                type: String
            },
            hide: {
                type: Boolean,
                value: true // init the value to true so it will be hidden on page load
            },
            metricScript: {
                type: String,
            },
            machineKeys: {
                type: Array,
                value: function () { return []; }
            },
            sshKeyExists: {
                type: Boolean,
                computed: "computeSshKeyExists(machineKeys)",
                value: true
            },
            uri: {
                type: String,
            },
            metric: {
                type: Object,
                value: function() {
                    return {
                        name: null,
                        unit: null,
                        type: "gauge",
                        script: "#!/usr/bin/env python\nimport random \n \ndef read(): \n    # return random value \n    return random.random() \n",
                        pluginId: null
                    }
                }
            }
        },
        observers: [
            '_metricScriptChanged(metricScript)'
        ],
        listeners: {
            'keyup': '_scriptValue',
            'panel-added': '_associateMetric'
        },
        _scriptValue: function (e) {
            if (e.target.id == "juicyScript") {
                this.set("metric.script", e.target.value.trim());
            }
        },
        _computeMetricsUri: function(machineId) {
            return "/api/v1/machines/" + machineId + "/metrics";
        },
        openDialog: function() {
            if (!this.responseMetrics) {
                this.shadowRoot.querySelector("#metrics").generateRequest();
            }
            this.shadowRoot.querySelector("#selectTarget").opened = true;
        },
        _handleMetricResponse: function(data) {
            console.log('_handleMetricResponse', data);
            var output = {};
            Object.keys(data.detail.response).forEach(function(i) {
                var res = output;
                var splitArray = i.split(".")
                for (var p = 0; p < splitArray.length; p++) {
                    if (!res[splitArray[p]]) {
                        res[splitArray[p]] = {};
                    }
                    if (p == splitArray.length - 1) {
                        res[splitArray[p]] = data.detail.response[i].id;
                    }
                    res = res[splitArray[p]];
                }
            });
            this.set('responseMetrics', output);
            this.set('responseMetricsArray', this._makeArray(output));
        },
        _makeArray: function(output) {
            var arr = [];
            if (output) {
                if (output && typeof(output) == 'object') {
                    var obj = {};
                    for (var p in output) {
                        if (typeof(output[p]) == 'object') {
                            obj = { name: p, options: this._makeArray(output[p]) };
                        } else {
                            obj = { name: output[p], options: [] };
                        }
                        arr.push(obj);
                    }
                }
            }
            return arr;
        },
        _showCustomGraphDialog: function() {
            this.$.customOptions.opened = true;
        },
        computeSshKeyExists: function(keys) {
            return keys.length > 0;
        },
        _openAddKeyPanel: function() {
            document.querySelector('#customOptions').opened = false;
            document.querySelector('#selectTarget').opened = false;
            this.dispatchEvent(new CustomEvent('open-and-select', {bubbles: true, composed: true}));
        },
        _metricScriptChanged: function(m) {
            // make sure long scripts don't push buttons out of the screen
            this.$.customOptions.refit();
        }
    });
    </script>
</dom-module>